﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BarCode.Common;
using System.IO;
using BarCode.Module;
using BarCode.AccessDao;
using System.Runtime.InteropServices;
using BarCode.Bean;
using System.IO.Ports;
using System.Threading;

namespace BarCode.Forms
{
    public partial class JXJK_BarCode : Form
    {
        [DllImport("user32.dll")]
        public static extern bool MessageBeep(uint uType);
        private static readonly log4net.ILog LogUtil = log4net.LogManager.GetLogger(typeof(JXJK_BarCode));


        private string WorkState = "";
        private string strValue = "";
        private string Jxstr = "";
        private string Jkstr = "";

        private bool bUpShell;
        private bool bDownShell;

        private string upShellHead;
        private string downShellHead;

        private string upShellCode = "";
        private string downShellCode = "";

        private int shellCodeLen = 12;


        private bool bFrame1;
        private bool bFrame2;

        private string frame1Head;
        private string frame2Head;

        private string frame1Code = "";
        private string frame2Code = "";

        private int frameCodeLen = 12;

        // 机芯机壳扫码顺序（默认值1：机芯机壳）
        private string jxjkOrder = "1";
        // 机壳机芯码验证规则
        private int JK_Len = 0;
        private string JK_Head = "";
        private int JX_Len = 0;
        private string JX_Head = "";

        private bool errorFlag = false;
        private string errMsg = "";

        // 机芯查找检查
        private bool jxCheck = true;
        // 本地Mysql保存
        private bool localMysqlSave = false;

        private SerialPort ComDevice = new SerialPort(); // 监视器串口
        private string stationNo = "";  // 工作区号
        private int workAmount = 0; // 工作量
        private bool jxCheckWarn = true;


        public JXJK_BarCode()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Base_BarCode_Load(object sender, EventArgs e)
        {
            // 读取机芯机壳扫码顺序
            jxjkOrder = IniFileHelper.ReadJxJkOrder();

            lblJkCode.Text = "";
            lblJxCode.Text = "";

            lblValue.Text = "";
            lblUser.Text = GlobalVal.CurrentUser.User;
            lblStatus.Text = "当前为正常工作状态！";
            lblstate.Text = "工作";
            lblstate.ForeColor = Color.Blue;
            WorkState = "工作";
            strValue = Consts.VAVLE_CODE;
            txtBarCode.Focus();
            if (GlobalVal.bolNetConnect)
            {
                btnNet.Enabled = false;
            }
            else
            {
                btnNet.Enabled = true;
            }

            // 加载配置文件
            if (!loadIniFile()) Application.Exit();  

            // 生成备份数据库
            string bakBarcodeMdb = GlobalVal.BK_PATH + "barcode_" + DateTime.Today.ToString("yyyyMMdd") + ".mdb";
            if (!File.Exists(bakBarcodeMdb))
            {
                if (!Directory.Exists(GlobalVal.BK_PATH))
                {
                    Directory.CreateDirectory(GlobalVal.BK_PATH);
                }
                // 复制文件
                FileHelper.CopyFile(AppDomain.CurrentDomain.BaseDirectory + "barcode.mdb", bakBarcodeMdb);
                FileHelper.CopyFile(AppDomain.CurrentDomain.BaseDirectory + "Empty_barcode.mdb", AppDomain.CurrentDomain.BaseDirectory + "barcode.mdb");
            }

            // 获取当前用户当天的工作量
            if (GlobalVal.bolNetConnect)
            {
                DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                GlobalVal.offSetInfo.jxjkoffset = db01.getOffSetValue(Consts.WORK_POSITION_JXJK);
                workAmount = db01.getJXJKWorkAmount(GlobalVal.CurrentUser.User);
                lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jxjkoffset).ToString();

                // 获取最新零件码信息
                JXJKBarCodeInfo latestInfo = db01.getJXJKLatestInfo();
                if (latestInfo != null)
                {
                    upShellCode = latestInfo.UpShellCode;
                    downShellCode = latestInfo.DownShellCode;
                }
            }
            else
            {
                BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                int workAmount = barcodeMdbDao.getJXJKWorkAmount(GlobalVal.CurrentUser.User);
                lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jxjkoffset).ToString();
            }
            txtBarCode.Text = "";
            txtBarCode.Focus();
            GlobalVal.jxjkCountI_OK = Convert.ToInt32(lblAmount.Text);
        }

        /// <summary>
        /// 加载配置文件
        /// </summary>
        /// <returns></returns>
        private bool loadIniFile()
        {
            // 读取机芯查找设置
            string jxCheckVal = IniFileHelper.ReadValue("JXJK", "JX_Check_Enable");
            if (!"1".Equals(jxCheckVal) && !String.IsNullOrEmpty(jxCheckVal))
            {
                jxCheck = false;
            }

            // 读取本地Mysql是否保存设置
            string localMysqlSaveVal = IniFileHelper.ReadValue("JXJK", "Local_MySql_Save");
            if (!String.IsNullOrEmpty(localMysqlSaveVal) && "1".Equals(localMysqlSaveVal))
            {
                localMysqlSave = true;
            }

            // 获取上下壳码的配置
            bUpShell = IniFileHelper.getBoolValue("JXJK", "UpShell_Enable");
            bDownShell = IniFileHelper.getBoolValue("JXJK", "DownShell_Enable");
            if (bUpShell)
            {
                upShellHead = IniFileHelper.getStringValue("JXJK", "UpShell_Head");
                if (String.IsNullOrEmpty(upShellHead))
                {
                    MessageUtil.Error("上壳的开头条码未设置，请设置后重启程序。");
                    return false;
                }
            }
            if (bDownShell)
            {
                downShellHead = IniFileHelper.getStringValue("JXJK", "DownShell_Head");
                if (String.IsNullOrEmpty(downShellHead))
                {
                    MessageUtil.Error("下壳的开头条码未设置，请设置后重启程序。");
                    return false;
                }
            }

            if (bUpShell || bDownShell)
            {
                shellCodeLen = IniFileHelper.getIntegerValue("JXJK", "Shell_Len");
                if (shellCodeLen < 0)
                {
                    MessageUtil.Error("上下壳码的长度设置不正确，请设置后重启程序。");
                    return false;
                }
            }


            // 获取框号的配置
            bFrame1 = IniFileHelper.getBoolValue("JXJK", "Frame1_Enable");
            bFrame2 = IniFileHelper.getBoolValue("JXJK", "Frame2_Enable");
            if (bFrame1)
            {
                frame1Head = IniFileHelper.getStringValue("JXJK", "Frame1_Head");
                if (String.IsNullOrEmpty(frame1Head))
                {
                    MessageUtil.Error("边框1的开头条码未设置，请设置后重启程序。");
                    return false;
                }
            }
            if (bFrame2)
            {
                frame2Head = IniFileHelper.getStringValue("JXJK", "Frame2_Head");
                if (String.IsNullOrEmpty(frame2Head))
                {
                    MessageUtil.Error("边框2的开头条码未设置，请设置后重启程序。");
                    return false;
                }
            }

            if (bFrame1 || bFrame2)
            {
                frameCodeLen = IniFileHelper.getIntegerValue("JXJK", "Frame_Len");
                if (frameCodeLen < 0)
                {
                    MessageUtil.Error("边框的长度设置不正确，请设置后重启程序。");
                    return false;
                }
            }

            stationNo = IniFileHelper.getStringValue("System", "Work_Station");
            if (string.IsNullOrEmpty(stationNo))
            {
                MessageUtil.Error("工位号未设置，请设置后重启程序。");
                return false;
            }

            // 获取机芯机壳码的校验规则配置
            JK_Len = IniFileHelper.getIntegerValue("JXJK", "JK_Len");
            if (JK_Len <= 0)
            {
                MessageUtil.Error("机壳码长度设置不正确，请设置后重启程序。");
                return false;
            }
            JX_Len = IniFileHelper.getIntegerValue("JXJK", "JX_Len");
            if (JX_Len <= 0)
            {
                MessageUtil.Error("机芯码长度设置不正确，请设置后重启程序。");
                return false;
            }
            JK_Head = IniFileHelper.getStringValue("JXJK", "JK_Head");
            if (string.IsNullOrEmpty(JK_Head))
            {
                MessageUtil.Error("机壳码开头码，请设置后重启程序。");
                return false;
            }
            JX_Head = IniFileHelper.getStringValue("JXJK", "JX_Head");
            if (string.IsNullOrEmpty(JX_Head))
            {
                MessageUtil.Error("机芯码开头码，请设置后重启程序。");
                return false;
            }


            // 加载监视器
            bool loadRet = ComUtil.LoadMonitor(ComDevice);
            if (!loadRet)
            {
                MessageUtil.Error("监视器无法连接，请设置正确串口后重启程序。");
                return false;
            }

            string jxCheckWarnVal = IniFileHelper.ReadValue("JXJK", "JX_Check_Warn");
            if (!"1".Equals(jxCheckWarnVal) && !String.IsNullOrEmpty(jxCheckWarnVal))
            {
                jxCheckWarn = false;
            }
            return true;
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Base_BarCode_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (GlobalVal.bolNetConnect)
            {
                GlobalVal.bolUploadSubMain = false;
                modeFunction.Upload_JxJkData();
            }
            Application.Exit();
        }

        /// <summary>
        /// 联通网络 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNet_Click(object sender, EventArgs e)
        {
            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            if (db01.EnableConnect() && Consts.CONNECT_SUCCESS.Equals(db01.getConnetText()))
            {
                GlobalVal.bolNetConnect = true;
                btnNet.Enabled = false;
            }
            else
            {
                GlobalVal.bolNetConnect = false;
                btnNet.Enabled = true;
            }
        }

        /// <summary>
        /// 二维码输入后回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {

            try
            {
                lblStatus.Text = "";
                lblStatus.ForeColor = Color.Blue;
                if (e.KeyChar == (char)13)
                {
                    // 是否是错误清除码
                    if (txtBarCode.Text.Equals(Consts.CLEAR_CODE))
                    {
                        errorFlag = false;
                        errMsg = "";

                        Jxstr = "";
                        lblJxCode.Text = "";

                        txtBarCode.Text = "";
                        txtBarCode.Focus();
                        return;
                    }


                    //if (errorFlag)
                    //{
                    //    lblStatus.Text = errMsg;
                    //    lblStatus.ForeColor = Color.Red;
                    //    txtBarCode.Text = "";
                    //    txtBarCode.Focus();
                    //    return;
                    //}


                    if ("1".Equals(jxjkOrder))
                    {
                        JxJkInputDeal();
                    }
                    else
                    {
                        JkJxInputDeal();
                    }

                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
                LogUtil.Debug("txtBarCode_KeyPress End");
                lblStatus.Text = "处理异常,请联系系统人员";
                lblStatus.ForeColor = Color.Red;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                return;
            }

        }

        /// <summary>
        /// 输入有误时弹框显示
        /// </summary>
        /// <param name="msg"></param>
        private void ShowInputWarn(string msg, uint beep)
        {
            txtBarCode.Text = "";
            txtBarCode.Focus();
            lblStatus.Text = msg;
            if (beep > 0)
            {
                MessageBeep(beep);
            }
        }


        private void JxJkInputDeal()
        {
            LogUtil.Debug("txtBarCode_KeyPress Start");
            LogUtil.Debug("输入BarCode检查----------");
            string inputBarCode = txtBarCode.Text;

            if (bUpShell && inputBarCode.StartsWith(upShellHead))
            {
                if (inputBarCode.Length != shellCodeLen)
                {
                    ShowInputWarn("上壳码的位数不正确！", Consts.MB_ICONASTERISK);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }

                upShellCode = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            if (bDownShell && inputBarCode.StartsWith(downShellHead))
            {
                if (inputBarCode.Length != shellCodeLen)
                {
                    ShowInputWarn("下壳码的位数不正确！", Consts.MB_ICONASTERISK);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }
                downShellCode = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            if (bFrame1 && inputBarCode.StartsWith(frame1Head))
            {
                if (inputBarCode.Length != frameCodeLen)
                {
                    ShowInputWarn("边框1的位数不正确！", Consts.MB_ICONASTERISK);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }

                frame1Code = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            if (bFrame2 && inputBarCode.StartsWith(frame2Head))
            {
                if (inputBarCode.Length != frameCodeLen)
                {
                    ShowInputWarn("边框2的位数不正确！", Consts.MB_ICONASTERISK);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }
                frame2Code = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            //// 条码长度检查
            //if (inputBarCode.Length != 8 && inputBarCode.Length != 11 && inputBarCode.Length != 12 && inputBarCode.Length != 26 && inputBarCode.Length != 14 && inputBarCode.Length != 13)
            //{
            //    LogUtil.Error("信息提示：条码信息位数不正确！ 所扫条码：" + inputBarCode);
            //    ShowInputWarn("条码信息位数不正确！", Consts.MB_ICONASTERISK);
            //    sendFail();
            //    return;
            //}

            if (inputBarCode.Equals(Consts.STATE_CODE1))
            {
                lblStatus.Text = "当前为正常工作状态！";
                lblstate.Text = "工作";
                lblstate.ForeColor = Color.Blue;
                WorkState = "工作";
                strValue = Consts.VAVLE_CODE;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                return;
            }
            else if (inputBarCode.Equals(Consts.JUDGE_CODE2))
            {
                lblStatus.Text = "您即将扫描不合格部件条码信息！";
                lblstate.Text = "返修";
                lblstate.ForeColor = Color.Red;
                WorkState = "返修";
                strValue = Consts.VAVLE_CODE;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                return;
            }

            if ("工作".Equals(WorkState))
            {
                //if (inputBarCode.StartsWith(Consts.JXCODE1) || inputBarCode.StartsWith(Consts.JXCODE2))
                if (inputBarCode.StartsWith(JX_Head))
                {
                    //// 11位时检查
                    //if (inputBarCode.Length == 11)
                    //{
                    //    if (inputBarCode.StartsWith("81"))
                    //    {
                    //        inputBarCode = "801" + inputBarCode.Substring(2);
                    //        txtBarCode.Text = inputBarCode;
                    //    }
                    //    else
                    //    {
                    //        LogUtil.Error("信息提示：无效条码信息不能扫描！ 所扫条码：" + inputBarCode);
                    //        ShowInputWarn("无效条码信息不能扫描！", 0);
                    //        sendFail();
                    //        return;
                    //    }
                    //}
                    if (inputBarCode.Length != JX_Len)
                    {
                        LogUtil.Error("信息提示：机芯码长度不正确！ 所扫条码：" + inputBarCode);
                        ShowInputWarn("机芯码长度不正确！", 0);
                        sendFail();
                        return;
                    }
                    Jxstr = inputBarCode;
                    lblJxCode.Text = Jxstr;
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    lblStatus.Text = "";

                    // 20191026 Add
                    // 检查机芯码是否存在
                    if (jxCheck)
                    {
                        DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                        bool existFlag = db01.CheckExistJXCode(Jxstr);
                        if (!existFlag)
                        {
                            // 不存在
                            errMsg = "机芯条码不存在";
                            lblStatus.Text = errMsg;
                            lblStatus.ForeColor = Color.Red;
                            errorFlag = true;

                            if (jxCheckWarn) sendFail();
                            return;
                        }
                    }

                    lblAmount.ForeColor = Color.Red;

                    sendInputing();
                    return;
                }
                //else if (inputBarCode.StartsWith(Consts.JKCODE))
                else if (inputBarCode.StartsWith(JK_Head))
                {
                    if ("".Equals(Jxstr))
                    {
                        LogUtil.Error("信息提示：机芯条码信息为空！ 所扫条码：" + inputBarCode);
                        Jxstr = "";
                        lblJxCode.Text = "";

                        Jkstr = "";
                        lblJkCode.Text = "";

                        txtBarCode.Text = "";
                        txtBarCode.Focus();
                        lblStatus.Text = "机芯条码信息为空！";
                        lblAmount.ForeColor = Color.Black;
                        sendFail();
                        return;
                    }

                    //// 11位时检查
                    //if (inputBarCode.Length == 11)
                    //{
                    //    if (inputBarCode.StartsWith("91"))
                    //    {
                    //        inputBarCode = "901" + inputBarCode.Substring(2);
                    //        txtBarCode.Text = inputBarCode;
                    //    }
                    //    else
                    //    {
                    //        LogUtil.Error("信息提示：无效条码信息不能扫描！ 所扫条码：" + inputBarCode);
                    //        ShowInputWarn("无效条码信息不能扫描！", 0);
                    //        sendFail();
                    //        return;
                    //    }
                    //}
                    if (inputBarCode.Length != JK_Len)
                    {
                        LogUtil.Error("信息提示：机壳码长度不正确！ 所扫条码：" + inputBarCode);
                        ShowInputWarn("机壳码长度不正确！", 0);
                        sendFail();
                        return;
                    }
                }
                else if (inputBarCode.Length == 26)
                {
                    strValue = inputBarCode;
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    if (!strValue.Trim().Equals(Consts.VAVLE_CODE))
                    {
                        lblStatus.Text = "即将安装金卡阀门";
                        lblValue.Text = "当前阀门条码：" + strValue;
                    }
                    else
                    {
                        lblStatus.Text = "即将安装其它类型";
                        lblValue.Text = "";
                    }
                    return;
                }
                else if (inputBarCode.Length == 8)
                {
                    strValue = inputBarCode;
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    if (!strValue.Trim().Equals(Consts.VAVLE_CODE))
                    {
                        lblStatus.Text = "即将安装安然阀门";
                        lblValue.Text = "当前阀门条码：" + strValue;
                    }
                    else
                    {
                        lblStatus.Text = "即将安装其它类型";
                        lblValue.Text = "";
                    }
                    return;
                }
                else
                {
                    LogUtil.Error("信息提示：无效条码信息不能扫描！ 所扫条码：" + inputBarCode);
                    ShowInputWarn("无效条码信息不能扫描！", 0);
                    sendFail();
                    return;
                }
                Jkstr = inputBarCode;
                lblJkCode.Text = Jkstr;

                if (bUpShell && String.IsNullOrEmpty(upShellCode))
                {
                    ShowInputWarn("上壳的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }
                if (bDownShell && String.IsNullOrEmpty(downShellCode))
                {
                    ShowInputWarn("下壳的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }
                if (bFrame1 && String.IsNullOrEmpty(frame1Code))
                {
                    ShowInputWarn("框号1的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }
                if (bFrame2 && String.IsNullOrEmpty(frame2Code))
                {
                    ShowInputWarn("框号2的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }


                JXJKBarCodeInfo jxjkBarCode = new JXJKBarCodeInfo();
                jxjkBarCode.JxBarcodeId = Jxstr;
                jxjkBarCode.JkBarcodeId = Jkstr;
                jxjkBarCode.VavleBarcodeId = strValue;
                jxjkBarCode.OperatorName = GlobalVal.CurrentUser.User;
                jxjkBarCode.UpShellCode = upShellCode;
                jxjkBarCode.DownShellCode = downShellCode;
                jxjkBarCode.frame1Code = frame1Code;
                jxjkBarCode.frame2Code = frame2Code;

                int resLs = Consts.RET_SUCCESS;
                //if (!jxCheck)
                if (localMysqlSave)
                {
                    LogUtil.Debug("添加扫描信息到本地JXJK Mysql----------");
                    // 添加扫描信息到本地Mysql
                    JXJKDBDao dbJxJk = new JXJKDBDao(GlobalVal.ipAddressInfo.JXJK_IP, GlobalVal.ipAddressInfo.JXJK_DBNAME, GlobalVal.JXJKMySQLInfo.USERID, GlobalVal.JXJKMySQLInfo.USERPWD);
                    resLs = dbJxJk.saveJKJXBarCode(jxjkBarCode);
                }

                LogUtil.Debug("扫描信息保存到本地MDB-----------------");
                // 保存到本地数据库
                BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                jxjkBarCode.OpDt = DateTime.Now;
                jxjkBarCode.markRepair = "合格";
                barcodeMdbDao.deleteJXJKBarCode(jxjkBarCode);
                int insCnt = barcodeMdbDao.insertJXJKBarCode(jxjkBarCode);
                barcodeMdbDao.Release();
                if (insCnt == 0)
                {
                    throw new Exception("保存失败");
                }

                if (resLs == Consts.RET_SUCCESS)
                {
                    if (!Consts.VAVLE_CODE.Equals(strValue))
                    {
                        lblValue.Text = "当前阀门条码：" + strValue;
                    }
                    else
                    {
                        lblValue.Text = "";
                    }
                    Jxstr = "";
                    lblJxCode.Text = "";

                    Jkstr = "";
                    lblJkCode.Text = "";

                    txtBarCode.Text = "";
                    txtBarCode.Focus();

                    if (GlobalVal.bolNetConnect == false)
                    {
                        if (GlobalVal.bolRepeats)
                        {
                            LogUtil.Error(lblStatus.Text + " 该表返修：机芯条码：" + GlobalVal.jxErrCode + " 机壳条码：" + GlobalVal.jkErrCode);
                            GlobalVal.bolRepeats = false;
                            lblStatus.Text = "";
                            GlobalVal.jxErrCode = "";
                            GlobalVal.jkErrCode = "";
                        }
                        GlobalVal.jxjkCountI_OK = GlobalVal.jxjkCountI_OK + 1;
                    }
                }
                else
                {
                    Jxstr = "";
                    lblJxCode.Text = "";

                    Jkstr = "";
                    lblJkCode.Text = "";

                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    LogUtil.Error("本地MySQL数据库出现问题");
                    lblStatus.Text = "本地MySQL数据库出现问题";
                    sendFail();
                    return;
                }
            }
            else if ("返修".Equals(WorkState))
            {
                if (inputBarCode.StartsWith(Consts.JKCODE))
                {
                    if (inputBarCode.StartsWith("91"))
                    {
                        inputBarCode = "901" + inputBarCode.Substring(2);
                        txtBarCode.Text = inputBarCode;
                    }
                    else
                    {
                        LogUtil.Error("信息提示：无效条码信息不能扫描！ 所扫条码：" + inputBarCode);
                        ShowInputWarn("无效条码信息不能扫描！", 0);
                        sendFail();
                        return;
                    }
                }
                else
                {
                    LogUtil.Error("非机壳条码信息不能扫描！ 所扫条码：" + inputBarCode);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }
                Jkstr = inputBarCode;
                lblJkCode.Text = Jkstr;

                LogUtil.Debug("添加扫描信息到本地JXJK Mysql----------");
                JXJKBarCodeInfo jxjkBarCode = new JXJKBarCodeInfo();
                jxjkBarCode.JkBarcodeId = Jkstr;
                JXJKDBDao dbJxJk = new JXJKDBDao(GlobalVal.ipAddressInfo.JXJK_IP, GlobalVal.ipAddressInfo.JXJK_DBNAME, GlobalVal.JXJKMySQLInfo.USERID, GlobalVal.JXJKMySQLInfo.USERPWD);
                int updRes = dbJxJk.updateJKRepaireStatus(jxjkBarCode);
                if (Consts.RET_NOTEXIST == updRes)
                {
                    LogUtil.Error("未找到要返修的条码信息！");
                    lblStatus.Text = "未找到要返修的条码信息！";
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                }

                LogUtil.Debug("扫描信息保存到本地MDB-----------------");
                // 本地MDB更新
                BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                jxjkBarCode.JxBarcodeId = Jxstr;
                jxjkBarCode.JkBarcodeId = Jkstr;
                jxjkBarCode.VavleBarcodeId = strValue;
                jxjkBarCode.OperatorName = GlobalVal.CurrentUser.User;
                jxjkBarCode.OpDt = DateTime.Now;
                jxjkBarCode.markRepair = "返修";
                barcodeMdbDao.updateJKRepairStatus(jxjkBarCode);
                barcodeMdbDao.Release();

                if (Consts.RET_FAIL == updRes)
                {
                    Jxstr = "";
                    lblJxCode.Text = "";

                    Jkstr = "";
                    lblJkCode.Text = "";

                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    LogUtil.Error("本地MySQL数据库出现问题");
                    lblStatus.Text = "本地MySQL数据库出现问题";
                    sendFail();
                    return;
                }
            }

            if (GlobalVal.bolNetConnect)
            {
                LogUtil.Debug("网络通直接上传数据-----------------");
                // 上传数据
                GlobalVal.bolUploadSubMain = false;
                modeFunction.Upload_JxJkData();
                lblStatus.Text = "";

                LogUtil.Debug("获取工作量信息---------------------");
                // 获取工作量信息
                DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                workAmount = db01.getJXJKWorkAmount(GlobalVal.CurrentUser.User);
                lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jxjkoffset).ToString();

                if (GlobalVal.bolRepeats)
                {
                    LogUtil.Error(lblStatus.Text + " 该表返修：机芯条码：" + GlobalVal.jxErrCode + " 机壳条码：" + GlobalVal.jkErrCode);
                    GlobalVal.bolRepeats = false;
                    lblStatus.Text = "";
                    GlobalVal.jxErrCode = "";
                    GlobalVal.jkErrCode = "";
                }

            }
            // 获取当前用户当天的工作量
            lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jxjkoffset).ToString();
            lblAmount.ForeColor = Color.Black;
            sendSuccess();

            txtBarCode.Text = "";
            txtBarCode.Focus();
            LogUtil.Debug("txtBarCode_KeyPress End");
        }


        private void JkJxInputDeal()
        {
            LogUtil.Debug("txtBarCode_KeyPress Start");
            LogUtil.Debug("输入BarCode检查----------");
            string inputBarCode = txtBarCode.Text;

            if (bUpShell && inputBarCode.StartsWith(upShellHead))
            {
                upShellCode = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            if (bDownShell && inputBarCode.StartsWith(downShellHead))
            {
                downShellCode = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            if (bFrame1 && inputBarCode.StartsWith(frame1Head))
            {
                if (inputBarCode.Length != frameCodeLen)
                {
                    ShowInputWarn("边框1的位数不正确！", Consts.MB_ICONASTERISK);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }

                frame1Code = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            if (bFrame2 && inputBarCode.StartsWith(frame2Head))
            {
                if (inputBarCode.Length != frameCodeLen)
                {
                    ShowInputWarn("边框2的位数不正确！", Consts.MB_ICONASTERISK);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }
                frame2Code = inputBarCode;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                lblStatus.Text = "";
                lblAmount.ForeColor = Color.Red;
                return;
            }

            //// 条码长度检查
            //if (inputBarCode.Length != 8 && inputBarCode.Length != 11 && inputBarCode.Length != 12 && inputBarCode.Length != 26 && inputBarCode.Length != 14 && inputBarCode.Length != 13)
            //{
            //    LogUtil.Error("信息提示：条码信息位数不正确！ 所扫条码：" + inputBarCode);
            //    ShowInputWarn("条码信息位数不正确！", Consts.MB_ICONASTERISK);
            //    sendFail();
            //    return;
            //}

            if (inputBarCode.Equals(Consts.STATE_CODE1))
            {
                lblStatus.Text = "当前为正常工作状态！";
                lblstate.Text = "工作";
                lblstate.ForeColor = Color.Blue;
                WorkState = "工作";
                strValue = Consts.VAVLE_CODE;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                return;
            }
            else if (inputBarCode.Equals(Consts.JUDGE_CODE2))
            {
                lblStatus.Text = "您即将扫描不合格部件条码信息！";
                lblstate.Text = "返修";
                lblstate.ForeColor = Color.Red;
                WorkState = "返修";
                strValue = Consts.VAVLE_CODE;
                txtBarCode.Text = "";
                txtBarCode.Focus();
                return;
            }

            if ("工作".Equals(WorkState))
            {

                //if (inputBarCode.StartsWith(Consts.JKCODE))
                if (inputBarCode.StartsWith(JK_Head))
                {
                    //// 11位时检查
                    //if (inputBarCode.Length == 11)
                    //{
                    //    if (inputBarCode.StartsWith("91"))
                    //    {
                    //        inputBarCode = "901" + inputBarCode.Substring(2);
                    //        txtBarCode.Text = inputBarCode;
                    //    }
                    //    else
                    //    {
                    //        LogUtil.Error("信息提示：无效条码信息不能扫描！ 所扫条码：" + inputBarCode);
                    //        ShowInputWarn("无效条码信息不能扫描！", 0);
                    //        sendFail();
                    //        return;
                    //    }
                    //}
                    if (inputBarCode.Length != JK_Len)
                    {
                        LogUtil.Error("信息提示：机壳码长度不正确！ 所扫条码：" + inputBarCode);
                        ShowInputWarn("机壳码长度不正确！", 0);
                        sendFail();
                        return;
                    }
                    Jkstr = inputBarCode;
                    lblJkCode.Text = inputBarCode;
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    lblStatus.Text = "";
                    lblAmount.ForeColor = Color.Red;
                    sendInputing();
                    return;
                }
                //else if (inputBarCode.StartsWith(Consts.JXCODE1) || inputBarCode.StartsWith(Consts.JXCODE2))
                else if (inputBarCode.StartsWith(JX_Head))
                {
                    if ("".Equals(Jkstr))
                    {
                        LogUtil.Error("信息提示：机壳条码信息为空！ 所扫条码：" + inputBarCode);
                        Jxstr = "";
                        lblJxCode.Text = "";

                        Jkstr = "";
                        lblJkCode.Text = "";

                        txtBarCode.Text = "";
                        txtBarCode.Focus();
                        lblStatus.Text = "机壳条码信息为空！";
                        lblAmount.ForeColor = Color.Black;
                        sendFail();
                        return;
                    }

                    //// 11位时检查
                    //if (inputBarCode.Length == 11)
                    //{
                    //    if (inputBarCode.StartsWith("81"))
                    //    {
                    //        inputBarCode = "801" + inputBarCode.Substring(2);
                    //        txtBarCode.Text = inputBarCode;
                    //    }
                    //    else
                    //    {
                    //        LogUtil.Error("信息提示：无效条码信息不能扫描！ 所扫条码：" + inputBarCode);
                    //        ShowInputWarn("无效条码信息不能扫描！", 0);
                    //        sendFail();
                    //        return;
                    //    }
                    //}
                    if (inputBarCode.Length != JX_Len)
                    {
                        LogUtil.Error("信息提示：机芯码长度不正确！ 所扫条码：" + inputBarCode);
                        ShowInputWarn("机芯码长度不正确！", 0);
                        sendFail();
                        return;
                    }
                }
                else if (inputBarCode.Length == 26)
                {
                    strValue = inputBarCode;
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    if (!strValue.Trim().Equals(Consts.VAVLE_CODE))
                    {
                        lblStatus.Text = "即将安装金卡阀门";
                        lblValue.Text = "当前阀门条码：" + strValue;
                    }
                    else
                    {
                        lblStatus.Text = "即将安装其它类型";
                        lblValue.Text = "";
                    }
                    return;
                }
                else if (inputBarCode.Length == 8)
                {
                    strValue = inputBarCode;
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    if (!strValue.Trim().Equals(Consts.VAVLE_CODE))
                    {
                        lblStatus.Text = "即将安装安然阀门";
                        lblValue.Text = "当前阀门条码：" + strValue;
                    }
                    else
                    {
                        lblStatus.Text = "即将安装其它类型";
                        lblValue.Text = "";
                    }
                    return;
                }
                
                Jxstr = inputBarCode;
                lblJxCode.Text = Jxstr;

                // 20191026 Add
                // 检查机芯码是否存在
                if (jxCheck)
                {
                    DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                    bool existFlag = db01.CheckExistJXCode(Jxstr);
                    if (!existFlag)
                    {
                        // 不存在
                        errMsg = "机芯条码不存在";
                        lblStatus.Text = errMsg;
                        lblStatus.ForeColor = Color.Red;
                        errorFlag = true;

                        if (jxCheckWarn) sendFail();
                        return;
                    }
                }

                if (bUpShell && String.IsNullOrEmpty(upShellCode))
                {
                    ShowInputWarn("上壳的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }
                if (bDownShell && String.IsNullOrEmpty(downShellCode))
                {
                    ShowInputWarn("下壳的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }
                if (bFrame1 && String.IsNullOrEmpty(frame1Code))
                {
                    ShowInputWarn("框号1的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }
                if (bFrame2 && String.IsNullOrEmpty(frame2Code))
                {
                    ShowInputWarn("框号2的条码未扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }

                JXJKBarCodeInfo jxjkBarCode = new JXJKBarCodeInfo();
                jxjkBarCode.JxBarcodeId = Jxstr;
                jxjkBarCode.JkBarcodeId = Jkstr;
                jxjkBarCode.VavleBarcodeId = strValue;
                jxjkBarCode.OperatorName = GlobalVal.CurrentUser.User;
                jxjkBarCode.UpShellCode = upShellCode;
                jxjkBarCode.DownShellCode = downShellCode;
                jxjkBarCode.frame1Code = frame1Code;
                jxjkBarCode.frame2Code = frame2Code;

                int resLs = Consts.RET_SUCCESS;
                //if (!jxCheck)
                if (localMysqlSave)
                {
                    LogUtil.Debug("添加扫描信息到本地JXJK Mysql----------");
                    // 添加扫描信息到本地Mysql
                    JXJKDBDao dbJxJk = new JXJKDBDao(GlobalVal.ipAddressInfo.JXJK_IP, GlobalVal.ipAddressInfo.JXJK_DBNAME, GlobalVal.JXJKMySQLInfo.USERID, GlobalVal.JXJKMySQLInfo.USERPWD);
                    resLs = dbJxJk.saveJKJXBarCode(jxjkBarCode);

                }
                LogUtil.Debug("扫描信息保存到本地MDB-----------------");
                // 保存到本地数据库
                BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                jxjkBarCode.OpDt = DateTime.Now;
                jxjkBarCode.markRepair = "合格";
                barcodeMdbDao.deleteJXJKBarCode(jxjkBarCode);
                barcodeMdbDao.insertJXJKBarCode(jxjkBarCode);
                barcodeMdbDao.Release();

                if (resLs == Consts.RET_SUCCESS)
                {
                    if (!Consts.VAVLE_CODE.Equals(strValue))
                    {
                        lblValue.Text = "当前阀门条码：" + strValue;
                    }
                    else
                    {
                        lblValue.Text = "";
                    }
                    Jxstr = "";
                    lblJxCode.Text = "";

                    Jkstr = "";
                    lblJkCode.Text = "";

                    txtBarCode.Text = "";
                    txtBarCode.Focus();

                    if (GlobalVal.bolNetConnect == false)
                    {
                        if (GlobalVal.bolRepeats)
                        {
                            LogUtil.Error(lblStatus.Text + " 该表返修：机芯条码：" + GlobalVal.jxErrCode + " 机壳条码：" + GlobalVal.jkErrCode);
                            GlobalVal.bolRepeats = false;
                            lblStatus.Text = "";
                            GlobalVal.jxErrCode = "";
                            GlobalVal.jkErrCode = "";
                        }
                        GlobalVal.jxjkCountI_OK = GlobalVal.jxjkCountI_OK + 1;
                    }
                }
                else
                {
                    Jxstr = "";
                    lblJxCode.Text = "";

                    Jkstr = "";
                    lblJkCode.Text = "";

                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    LogUtil.Error("本地MySQL数据库出现问题");
                    lblStatus.Text = "本地MySQL数据库出现问题";
                    sendFail();
                    return;
                }
            }
            else if ("返修".Equals(WorkState))
            {
                if (inputBarCode.StartsWith(Consts.JKCODE))
                {
                    if (inputBarCode.StartsWith("91"))
                    {
                        inputBarCode = "901" + inputBarCode.Substring(2);
                        txtBarCode.Text = inputBarCode;
                    }
                    else
                    {
                        LogUtil.Error("信息提示：无效条码信息不能扫描！ 所扫条码：" + inputBarCode);
                        ShowInputWarn("无效条码信息不能扫描！", 0);
                        sendFail();
                        return;
                    }
                }
                else
                {
                    LogUtil.Error("非机壳条码信息不能扫描！ 所扫条码：" + inputBarCode);
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    sendFail();
                    return;
                }
                Jkstr = inputBarCode;
                lblJkCode.Text = Jkstr;

                LogUtil.Debug("添加扫描信息到本地JXJK Mysql----------");
                JXJKBarCodeInfo jxjkBarCode = new JXJKBarCodeInfo();
                jxjkBarCode.JkBarcodeId = Jkstr;
                JXJKDBDao dbJxJk = new JXJKDBDao(GlobalVal.ipAddressInfo.JXJK_IP, GlobalVal.ipAddressInfo.JXJK_DBNAME, GlobalVal.JXJKMySQLInfo.USERID, GlobalVal.JXJKMySQLInfo.USERPWD);
                int updRes = dbJxJk.updateJKRepaireStatus(jxjkBarCode);
                if (Consts.RET_NOTEXIST == updRes)
                {
                    LogUtil.Error("未找到要返修的条码信息！");
                    lblStatus.Text = "未找到要返修的条码信息！";
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                }

                LogUtil.Debug("扫描信息保存到本地MDB-----------------");
                // 本地MDB更新
                BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                jxjkBarCode.JxBarcodeId = Jxstr;
                jxjkBarCode.JkBarcodeId = Jkstr;
                jxjkBarCode.VavleBarcodeId = strValue;
                jxjkBarCode.OperatorName = GlobalVal.CurrentUser.User;
                jxjkBarCode.OpDt = DateTime.Now;
                jxjkBarCode.markRepair = "返修";
                barcodeMdbDao.updateJKRepairStatus(jxjkBarCode);
                barcodeMdbDao.Release();

                if (Consts.RET_FAIL == updRes)
                {
                    Jxstr = "";
                    lblJxCode.Text = "";

                    Jkstr = "";
                    lblJkCode.Text = "";

                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    LogUtil.Error("本地MySQL数据库出现问题");
                    lblStatus.Text = "本地MySQL数据库出现问题";
                    sendFail();
                    return;
                }
            }

            if (GlobalVal.bolNetConnect)
            {
                LogUtil.Debug("网络通直接上传数据-----------------");
                // 上传数据
                GlobalVal.bolUploadSubMain = false;
                modeFunction.Upload_JxJkData();
                lblStatus.Text = "";

                LogUtil.Debug("获取工作量信息---------------------");
                // 获取工作量信息
                DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                workAmount = db01.getJXJKWorkAmount(GlobalVal.CurrentUser.User);
                lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jxjkoffset).ToString();

                if (GlobalVal.bolRepeats)
                {
                    LogUtil.Error(lblStatus.Text + " 该表返修：机芯条码：" + GlobalVal.jxErrCode + " 机壳条码：" + GlobalVal.jkErrCode);
                    GlobalVal.bolRepeats = false;
                    lblStatus.Text = "";
                    GlobalVal.jxErrCode = "";
                    GlobalVal.jkErrCode = "";
                }

            }
            // 获取当前用户当天的工作量
            lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jxjkoffset).ToString();
            lblAmount.ForeColor = Color.Black;
            sendSuccess();

            txtBarCode.Text = "";
            txtBarCode.Focus();
            LogUtil.Debug("txtBarCode_KeyPress End");
        }


        private bool LoadMonitor(string portName)
        {
            ComDevice.PortName = portName;
            ComDevice.BaudRate = 9600;
            ComDevice.Parity = Parity.Even;
            ComDevice.DataBits = 8;
            ComDevice.StopBits = StopBits.One;
            try
            {
                ComDevice.Open();
                return true;
            }
            catch (Exception ex)
            {
                lblStatus.Text = ex.Message;
                LogUtil.Error("串口打开异常", ex);
                return false;
            }

        }

        /// <summary>
        /// 发送成功指令
        /// </summary>
        /// <param name="workAmount"></param>
        private void sendSuccess()
        {
            try
            {
                string sendCode = ComUtil.createSuccessCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);

            }
            catch (Exception ex)
            {
                LogUtil.Error("发送成功指令异常发生", ex);
            }
        }


        /// <summary>
        /// 发送输入中指令
        /// </summary>
        /// <param name="workAmount"></param>
        private void sendInputing()
        {
            try
            {
                string sendCode = ComUtil.createInputingCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);

            }
            catch (Exception ex)
            {
                LogUtil.Error("发送输入中指令异常发生", ex);
            }
        }

        /// <summary>
        /// 发送失败指令
        /// </summary>
        /// <param name="workAmount"></param>
        private void sendFail()
        {
            try
            {
                string sendCode = ComUtil.createFailCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);

                // 1秒后发送停止警报命令
                Thread.Sleep(1000);
                sendStopWarn();
            }
            catch (Exception ex)
            {
                LogUtil.Error("发送失败指令异常发生", ex);
            }
        }

        /// <summary>
        /// 发送停鸣指令
        /// </summary>
        private void sendStopWarn()
        {
            try
            {
                string sendCode = ComUtil.createStopWarnCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);
            }
            catch (Exception ex)
            {
                LogUtil.Error("发送停鸣指令异常发生", ex);
            }
        }

    }
}
